import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2022-10-25
 * Time: 19:50
 */
public class Task {
    //相交链表
    public static ListNode  getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode maxp = headA;
        ListNode p  = headB;
        //1.求链表的长度
        int maxl = size(headA);
        int l = size(headB);
        int len = maxl - l;
        //2.maxp永远指向最长的链表，p指向最短的链表
        if(len < 0){
            maxp = headB;
            p = headA;
            len = l - maxl;
        }
        while (len > 0){
            maxp = maxp.next;
            len--;
        }
        //3.maxp和p在相同的起始位置
        while (maxp != p){
            maxp = maxp.next;
            p = p.next;
        }
        //当maxp == p == null
        if(maxp == null){
            return null;
        }
        return maxp;
    }
    private static int size(ListNode p){
       if(p == null){
           return 0;
       }
       int count = 0;
       while (p != null){
           count++;
           p = p.next;
       }
       return count;
    }

}
